<template>
  <div style="height: 100vh; display: flex; flex-direction: column; background: #f5f5f5;">
    <!-- 顶部导航栏 - 固定高度 -->
    <div style="height: 80px; background: white; border-bottom: 1px solid #ddd; display: flex; align-items: center; padding: 0 30px; flex-shrink: 0;">
      <a-button type="link" @click="goBack" style="padding: 0; margin-right: 20px; font-size: 16px;">
        <LeftOutlined />
        返回
      </a-button>
      <h1 style="color: #1890ff; margin: 0; font-size: 24px;">案件详情</h1>
    </div>
    
    <!-- 主体内容 -->
    <div style="flex: 1; padding: 40px 20px; background: #f5f5f5;">
        <div v-if="caseData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); width: 100%;">
          <!-- 案件基本信息 -->
          <div style="border-bottom: 1px solid #f0f0f0; padding-bottom: 30px; margin-bottom: 30px;">
            <h2 style="font-size: 28px; color: #333; margin-bottom: 20px;">{{ caseData.caseNumber }}</h2>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
              <div>
                <span style="font-weight: 600; color: #666;">当事人：</span>
                <span style="font-size: 16px;">{{ caseData.parties }}</span>
              </div>
              
              <div>
                <span style="font-weight: 600; color: #666;">审理法院：</span>
                <span style="font-size: 16px;">{{ caseData.court }}</span>
              </div>
              
              <div>
                <span style="font-weight: 600; color: #666;">案件状态：</span>
                <a-tag :color="getStatusColor(caseData.status)" style="margin-left: 8px;">
                  {{ getStatusText(caseData.status) }}
                </a-tag>
              </div>
              
              <div>
                <span style="font-weight: 600; color: #666;">创建时间：</span>
                <span style="font-size: 16px;">{{ caseData.createTime }}</span>
              </div>
            </div>
          </div>
          
          <!-- 案件详细信息 -->
          <div>
            <h3 style="font-size: 20px; color: #333; margin-bottom: 20px;">案件详细信息</h3>
            <div style="background: #fafafa; padding: 20px; border-radius: 8px; line-height: 1.8; font-size: 16px;">
              <p>这里是案件的详细信息内容，包括案件的背景、争议焦点、法律适用、判决结果等详细信息。</p>
              <p>可以根据实际的案件数据来展示更多的信息内容。</p>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮区域 -->
        <div v-if="caseData.id" style="background: white; padding: 20px 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 30px; display: flex; justify-content: flex-end; gap: 12px;">
          <a-button 
            :type="isFavorited ? 'primary' : 'default'" 
            @click="handleToggleFavorite"
            :loading="favoriteLoading"
          >
            {{ isFavorited ? '已收藏' : '收藏' }}
          </a-button>
        </div>
        
        <!-- 评论区域 -->
        <div v-if="caseData.id" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="font-size: 18px; color: #333; margin: 0; display: flex; align-items: center;">
              <span style="margin-right: 8px;">💬</span>
              评论 ({{ commentsPagination.total }})
            </h3>
          </div>
          
          <!-- 发表评论 -->
          <div style="margin-bottom: 30px; padding: 20px; background: #fafafa; border-radius: 8px;">
            <a-textarea
              v-model:value="newComment"
              placeholder="请输入您的评论..."
              :rows="4"
              :max-length="500"
              show-count
              style="margin-bottom: 12px;"
            />
            <a-button type="primary" @click="handleAddComment" :loading="commentLoading">
              发表评论
            </a-button>
          </div>
          
          <!-- 评论列表 -->
          <a-spin :spinning="commentsLoading">
            <div v-if="comments.length > 0" style="display: flex; flex-direction: column; gap: 16px;">
              <div v-for="comment in comments" :key="comment.id" 
                   style="background: #fafafa; border-radius: 8px; padding: 20px; border: 1px solid #f0f0f0; transition: all 0.3s;">
                <div style="display: flex; align-items: flex-start; gap: 16px;">
                  <a-avatar :size="44" :src="comment.userAvatar" style="flex-shrink: 0;">
                    {{ comment.username?.charAt(0)?.toUpperCase() }}
                  </a-avatar>
                  <div style="flex: 1; min-width: 0;">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px;">
                      <div>
                        <div style="font-weight: 600; font-size: 15px; color: #333; margin-bottom: 4px;">{{ comment.username }}</div>
                        <div style="font-size: 13px; color: #999;">{{ comment.createTime }}</div>
                      </div>
                      <a-button 
                        v-if="comment.userId === currentUserId" 
                        type="text" 
                        danger 
                        size="small"
                        @click="handleDeleteComment(comment.id)"
                        style="margin-top: -4px;"
                      >
                        删除
                      </a-button>
                    </div>
                    <p style="margin: 0; color: #555; font-size: 15px; line-height: 1.8; word-break: break-word;">
                      {{ comment.content }}
                    </p>
                  </div>
                </div>
              </div>
              
              <div v-if="commentsPagination.total > commentsPagination.pageSize" style="text-align: center; margin-top: 20px;">
                <a-pagination
                  v-model:current="commentsPagination.current"
                  v-model:page-size="commentsPagination.pageSize"
                  :total="commentsPagination.total"
                  :show-size-changer="false"
                  :show-quick-jumper="true"
                  @change="loadComments"
                />
              </div>
            </div>
            
            <div v-else style="text-align: center; padding: 40px; color: #999;">
              <div style="font-size: 36px; margin-bottom: 12px;">💭</div>
              <p>暂无评论，快来发表第一条评论吧！</p>
            </div>
          </a-spin>
        </div>
        
        <div v-else-if="!loading" style="background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); text-align: center;">
          <p style="font-size: 16px; color: #999;">案件信息不存在或加载失败</p>
        </div>
        
        <div v-if="loading" style="text-align: center; padding: 100px;">
          <a-spin size="large">
            <div style="margin-top: 20px; font-size: 16px; color: #666;">加载中...</div>
          </a-spin>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCaseDetail } from '@/api/case'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getCommentPage, addComment, deleteComment } from '@/api/comment'
import { checkFavorite, toggleFavorite } from '@/api/favorite'
import { getCurrentUserInfo } from '@/api/user'

const route = useRoute()
const router = useRouter()

const caseData = ref({})
const comments = ref([])
const loading = ref(false)
const commentsLoading = ref(false)
const commentLoading = ref(false)
const favoriteLoading = ref(false)

// 收藏状态
const isFavorited = ref(false)
const currentUserId = ref(null)

// 评论表单
const newComment = ref('')

// 分页状态
const commentsPagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
})

// 获取案件详情
const loadCaseDetail = async (id) => {
  try {
    loading.value = true
    const response = await getCaseDetail(id)
    caseData.value = response.data || {}
  } catch (error) {
    console.error('获取案件详情出错:', error)
    // 如果接口失败，显示模拟数据
    caseData.value = {
      id: id,
      caseNumber: `案件编号-${id}`,
      parties: '示例当事人A vs 示例当事人B',
      court: '示例人民法院',
      status: 1,
      createTime: '2024-01-01 10:00:00'
    }
  } finally {
    loading.value = false
  }
  
  // 加载相关数据
  if (caseData.value.id) {
    loadComments()
    checkFavoriteStatus()
  }
}

// 获取案件状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '进行中',
    1: '已结案', 
    2: '上诉'
  }
  return statusMap[status] || '未知'
}

// 获取案件状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: 'processing',
    1: 'success',
    2: 'warning'
  }
  return colorMap[status] || 'default'
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 加载评论
const loadComments = async () => {
  try {
    commentsLoading.value = true
    const response = await getCommentPage({
      caseId: caseData.value.id, // 注意这里是caseId，不是documentId
      pageNum: commentsPagination.value.current,
      pageSize: commentsPagination.value.pageSize
    })
    if (response.code === 200) {
      comments.value = response.data.records || []
      commentsPagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取评论出错:', error)
  } finally {
    commentsLoading.value = false
  }
}

// 发表评论
const handleAddComment = async () => {
  if (!newComment.value.trim()) {
    message.warning('请输入评论内容')
    return
  }
  
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录')
    return
  }
  
  try {
    commentLoading.value = true
    const response = await addComment({
      caseId: caseData.value.id, // 注意这里是caseId
      content: newComment.value.trim()
    })
    if (response.code === 200) {
      message.success('评论发表成功')
      newComment.value = ''
      commentsPagination.value.current = 1
      loadComments()
    } else {
      message.error(response.msg || '评论发表失败')
    }
  } catch (error) {
    console.error('发表评论出错:', error)
    message.error('评论发表失败')
  } finally {
    commentLoading.value = false
  }
}

// 删除评论
const handleDeleteComment = async (commentId) => {
  try {
    const response = await deleteComment(commentId)
    if (response.code === 200) {
      message.success('评论删除成功')
      loadComments()
    } else {
      message.error(response.msg || '评论删除失败')
    }
  } catch (error) {
    console.error('删除评论出错:', error)
    message.error('评论删除失败')
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    const response = await checkFavorite({
      caseId: caseData.value.id // 注意这里是caseId
    })
    if (response.code === 200) {
      isFavorited.value = response.data || false
    }
  } catch (error) {
    console.error('检查收藏状态出错:', error)
  }
}

// 切换收藏状态
const handleToggleFavorite = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录')
    return
  }
  
  try {
    favoriteLoading.value = true
    const response = await toggleFavorite({
      caseId: caseData.value.id // 注意这里是caseId
    })
    if (response.code === 200) {
      isFavorited.value = !isFavorited.value
      message.success(isFavorited.value ? '收藏成功' : '取消收藏成功')
    } else {
      message.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏状态出错:', error)
    message.error('操作失败')
  } finally {
    favoriteLoading.value = false
  }
}

// 获取当前用户信息
const loadCurrentUser = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    const response = await getCurrentUserInfo()
    if (response.code === 200) {
      currentUserId.value = response.data.id
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
  }
}

// 页面加载时获取案件详情
onMounted(() => {
  const caseId = route.params.id
  if (caseId) {
    loadCaseDetail(caseId)
    loadCurrentUser()
  }
})
</script>

<style>
/* 基础样式 */
</style>